<?php
namespace Home\Controller;

use Think\Controller;

class ApiController extends CommonController
{
    /**
     * 构建函数
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function imgUpload()
    {
        Vendor('Wechat/Wechat');
        $media_id = I('post.media_id', '');
        if (!$media_id) {
            error(6007, 'media_id参数错误');
        }

        $wechat = new \Wechat(C('WX_CONF'));
        $img    = $wechat->getMedia($media_id);
        
        $file_name = generate_img_name();

        $path   = '/Uploads/Red_Image/';
        $result = file_put_contents(WEB_PATH . $path . $file_name, $img);

        if ($result  !== false) {
            success([
                'image' => $path . $file_name,
            ]);
        } else {
            error(6008, '图片上传失败');
        }

    }

    public function voiceUpload()
    {
        Vendor('Wechat/Wechat');
        $media_id = I('post.media_id', '5U_Hx862yShmQ7yPZ8II0EDOaC4neupAnkDxryeeWsBAdoLN5BlyqvCEfvN13gJc');
        if (!$media_id) {
            error(6007, 'media_id参数错误');
        }

        $wechat = new \Wechat(C('WX_CONF'));
        $img    = $wechat->getMedia($media_id);

        $file_name = generate_voice_name();

        $path   = '/Uploads/Red_Voice/';
        $result = file_put_contents(WEB_PATH . $path . $file_name, $img);

        if ($result !== false) {

            $new_file = $this->amr2wav(WEB_PATH . $path . $file_name);

            if ($new_file) {

                success([
                    'video' => $new_file,
                ]);

            } else {

                error(6010, '语音转换失败');
            }
        } else {
            error(6009, '语音上传失败');
        }
    }

    /**
     * 此方法需要安装ffmpeg 具体方法可百度或geogle
     * @return [type] [description]
     */
    private function amr2wav($file)
    {
        $new_file = basename($file, '.amr');

        $command = 'ffmpeg -i ' . $file . ' ' . $new_file . '.wav';

        $result = exec($command);

        return $new_file . '.wav';
    }
}
